<template>
  <div id="editPicturePage">
    <h2 style="margin-bottom: 16px; text-align: center">编辑图片</h2>
    <a-typography-paragraph v-if="spaceId" type="secondary" style="text-align: center">
      保存至个人云：<a :href="`/space/${spaceId}`" target="_blank"> {{ spaceId }}</a>
    </a-typography-paragraph>
    <a-typography-paragraph v-if="picture" type="secondary" style="text-align: center">
      点击图片可重新上传
    </a-typography-paragraph>
    <!-- 图片上传组件 -->
    <PictureUpload :picture="picture" :spaceId="spaceId" :on-success="onSuccess" />
    <!-- 图片裁剪、AI扩图 两个按钮区域 -->
    <div v-if="picture" class="crop-bar">
      <a-space size="large">
        <a-button :icon="h(ScissorOutlined)" @click="doCropPicture">裁剪图片</a-button>
        <a-button :icon="h(ExpandOutlined)" @click="doExpandOutPicture">AI 扩图 </a-button>
      </a-space>
      <ImageCropper
        ref="imageCropperRef"
        :imageUrl="picture?.url"
        :picture="picture"
        :spaceId="picture?.spaceId"
        :space="space"
        :onSuccess="onCropSuccess"
      />
      <ImageOutPainting
        ref="imageOutPaintingRef"
        :picture="picture"
        :spaceId="picture?.spaceId"
        :onSuccess="onOutPaintingSuccess"
      />
    </div>
    <!-- 图片信息表单 -->
    <a-form v-if="picture" layout="vertical" :model="pictureForm" @finish="handleSubmit">
      <a-form-item label="图片名称" name="name">
        <a-input
          v-model:value="pictureForm.name"
          placeholder="请输入图片名"
          style="max-width: 320px"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="图片简介" name="introduction">
        <a-textarea
          v-model:value="pictureForm.introduction"
          placeholder="介绍一下这个图片吧"
          :autoSize="{ minRows: 1, maxRows: 5 }"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="图片分类" name="category">
        <a-auto-complete
          v-model:value="pictureForm.category"
          placeholder="可自定义图片分类"
          :options="categoryOptions"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="图片标签" name="tags">
        <a-select
          v-model:value="pictureForm.tags"
          mode="tags"
          placeholder="可自定义图片标签"
          :options="tagOptions"
          allow-clear
        />
      </a-form-item>
      <a-form-item>
        <a-flex>
          <a-button type="text" danger @click="cancelEditPicture" block :icon="h(CloseOutlined)">
            取消修改
          </a-button>
          <a-button
            :icon="h(FileSyncOutlined)"
            type="primary"
            :loading="loading"
            html-type="submit"
            style="width: 100%"
          >
            提交修改
          </a-button>
        </a-flex>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import PictureUpload from '@/components/PictureUpload.vue'
import { onMounted, reactive, ref, h, computed, watch, watchEffect } from 'vue'
import {
  editPictureUsingPost,
  getPictureVoByIdUsingGet,
  listPictureTagCategoryUsingGet,
} from '@/api/pictureController.ts'
import {
  CloseOutlined,
  ExpandOutlined,
  FileSyncOutlined,
  ScissorOutlined,
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import ImageCropper from '@/components/ImageCropper.vue'
import { useLoginUserStore } from '@/stores/useLoginUserStores.ts'
import ImageOutPainting from '@/components/ImageOutPainting.vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController.ts'

const picture = ref<API.PictureVO>()
// 图片信息表单，类型是编辑图片请求体，默认是空对象
const pictureForm = reactive<API.PictureEditRequest>({})

// 如果要上传图到个人云，获取空间Id，并用计算属性包裹
const spaceId = computed(() => {
  return route.query?.spaceId
})

/**
 * 图片上传成功，回显图片和图片名称
 * @param newPicture
 */
const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  pictureForm.name = newPicture.name
}

const router = useRouter()

const loginUserStore = useLoginUserStore()
const loginUser = loginUserStore.loginUser

const loading = ref(false)

/**
 * 提交表单编辑图片
 * @param values
 */
const handleSubmit = async (values: any) => {
  loading.value = true
  if (!loginUser) {
    message.error('请先登录')
    loading.value = false
    return
  }
  // 已经改为使用后端提供的统一的权限校验
  // if (loginUser?.id !== picture.value?.userId) {
  //   message.error('无权编辑图片')
  //   loading.value = false
  //   return
  // }
  const pictureId = picture.value?.id
  if (!pictureId) {
    return
  }
  const res = await editPictureUsingPost({
    id: pictureId,
    spaceId: spaceId.value,
    ...values,
  })
  if (res.data.code === 0 && res.data.data) {
    message.success('修改图片信息成功')
    // 修改成功后返回上一页
    router.back()
  } else {
    message.error('修改失败，' + res.data.message)
  }
  loading.value = false
}

/**
 * 取消修改图片信息
 */
const cancelEditPicture = () => {
  message.success('取消修改图片成功')
  router.back()
}

// 监听图片名长度，超过18个字符给出警告
watch(
  () => pictureForm.name,
  (newName) => {
    if (newName && newName.length > 18) {
      message.warn('图片名至多 18 个字符，请适当缩短')
    }
  },
)
// 监听图片简介长度，超过80个字符给出警告
watch(
  () => pictureForm.introduction,
  (newIntroduction) => {
    if (newIntroduction && newIntroduction.length > 80) {
      message.warn('图片简介至多 80 个字符，请适当缩短')
    }
  },
)
// 监听图片标签数量，超过6个标签给出警告
watch(
  () => pictureForm.tags,
  (newTags) => {
    if (newTags && newTags.length > 6) {
      message.warn('标签数量至多 6 个，请适当减少')
    }
  },
  { deep: true },
)

const categoryOptions = ref<String[]>([])
const tagOptions = ref<String[]>()

/**
 * 进入创建图片页面 展示默认标签和分类选项
 */
const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    // @ts-ignore
    tagOptions.value = (res.data.data.tagList ?? []).map((data: String) => {
      return {
        value: data,
        label: data,
      }
    })
    // @ts-ignore
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: String) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('默认分类标签列表展示失败，' + res.data.message)
  }
}

// 监听图片名长度，超过18个字符给出警告
watch(
  () => pictureForm.name,
  (newName) => {
    if (newName && newName.length > 18) {
      message.warn('图片名至多18个字符，请适当缩短')
    }
  },
)

onMounted(() => {
  getTagCategoryOptions()
})

const route = useRoute()

/**
 * 根据id获取老图片
 */
const getOldPicture = async () => {
  // 获取到id
  const id = route.query?.id
  if (id) {
    const res = await getPictureVoByIdUsingGet({
      // @ts-ignore
      id,
    })
    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data
      picture.value = data
      pictureForm.name = data.name
      pictureForm.introduction = data.introduction
      pictureForm.category = data.category
      pictureForm.tags = data.tags
    }
  }
}
/**
 * 根据route上的图片id展示老图片
 */
onMounted(() => {
  getOldPicture()
})

// 图片裁剪器引用
const imageCropperRef = ref()
// 裁切图片函数
const doCropPicture = () => {
  // 打开裁切弹窗
  imageCropperRef.value?.openModal()
}
// 裁剪成功事件
const onCropSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

// 扩图器引用
const imageOutPaintingRef = ref()
// AI 扩图函数
const doExpandOutPicture = () => {
  imageOutPaintingRef.value?.openModal()
}
// 扩图成功且上传成功事件
const onOutPaintingSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

/**
 * 获取图片对应的空间
 */
const space = ref<API.SpaceVO>()

const fetchSpace = async () => {
  const res = await getSpaceVoByIdUsingGet({
    id: picture.value?.spaceId,
  })
  if (res.data.code === 0 && res.data.data) {
    space.value = res.data.data
  } else {
  }
}
watchEffect(() => {
  fetchSpace()
})
</script>

<style scoped>
#editPicturePage {
  max-width: 580px;
  margin: 0 auto;
}

#editPicturePage .crop-bar {
  text-align: center;
  margin-top: 3px;
}
</style>
